import { InputItem as AntInput } from 'antd-mobile-v2';
import * as React from 'react';
import { Props, State } from '../type';
import { IOrgTreeCheckedItem } from '../interface';
import ContractSelectModal from '@/components/ContractSelectModal';
import { connect } from 'react-redux';
import { ConnectState, ConnectProps } from 'typings/connect';
import './index.less';
export class ContractSelect extends React.Component<Props & ConnectProps, State> {
  public static defaultProps = new Props();
  public state = new State();
  constructor(props: Props) {
    super(props);
    this.state = {
      modalStatus: false,
      showSelectedName: '',
      receiveData: []
    };
  }

  UNSAFE_componentWillMount() {
    this.setReceiveData();
  }

  componentDidMount() {
    this.props.getOrgTree();
  }

  componentDidUpdate(_prevProps, prevState) {
    this.setReceiveData(prevState);
  }

  setReceiveData = (prevState?: any) => {
    const { props: { form, code } } = this;
    const value = form?.getFieldValue(code);
    if (prevState && prevState?.receiveData.length === value?.length) return; // 避免过多更新导致异常
    if (!value) return;
    this.setState({
      receiveData: value
    });
  }

  handleKeyPress = () => {
    this.setState({ modalStatus: true });
    document.documentElement.style.overflow = 'hidden';
    document.body.style.overflow = 'hidden';
  };

  closeModal() {
    document.documentElement.style.overflow = '';
    document.body.style.overflow = '';
    this.setState({ modalStatus: false });
  }

  onSubmit = (isHandle: boolean, values: IOrgTreeCheckedItem[], fieldProps: any) => {
    const result = values?.map((el) => {
      return {
        value: el.key,
        text: el.title,
        type: el.type
      };
    });
    this.setState({ modalStatus: false }
    );
    const { props: { form, code } } = this;
    document.documentElement.style.overflow = '';
    document.body.style.overflow = '';
    //先触发一次getFieldProps的onChange方法，标记当前表单已经被手动操作过，用于识别表单编辑后路由离开拦截
    if (isHandle) fieldProps?.onChange(result);
    this.props.onChange && this.props.onChange(result);
    form && form.setFieldsValue({ [code]: result });
  };

  getCheckedValue = () => {
    const { props: { form, code } } = this;
    const value = form?.getFieldValue(code);
    if (!value) {
      return '';
    }
    let texts = value?.map(({ text }) => text);
    texts = texts.join('，');
    if (texts.length > 11) {
      return `${texts.slice(0, 11)}...`;
    }
    return texts;
  };

  onClear = () => {
    this.props.onChange && this.props.onChange([]);
  };


  public render() {
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    const { getFieldProps } = this.props.form || {};
    const {
      form,
      name,
      orgTree,
      placeholder
    } = this.props;


    let fieldProps: any = {};

    if (getFieldProps) {
      fieldProps = {
        ...getFieldProps(this.props.code, {
          rules: [
            { required: this.props.required, message: `请选择${name}` }
          ]
        })
      };
    }

    return (
      <>
        <div className="selectWrap" onClick={this.handleKeyPress}>
          <AntInput
            title={form ? form.getFieldValue(this.props.code) : ''}
            type="text"
            min={0}
            editable={false}
            {...fieldProps}
            disabled
            autoAdjustHeight
            value={this.getCheckedValue()}
            placeholder={placeholder}
            extra={<i className="icon iconfont" style={{ fontSize: '16px', color: '#d1d1d1', position: 'relative', right: '-0.6vw' }}>&#xe6ed;</i>}
            style={{ color: '#222' }}
          >
            {name}
          </AntInput>
        </div>
        <ContractSelectModal
          modalStatus={this.state.modalStatus}
          closeModal={this.closeModal.bind(this)}
          submit={(isHandle: boolean, value: any[]) => { this.onSubmit(isHandle, value, fieldProps); }}
          type={this.props.onlyUser === false ? 'all' : 'person'}
          receiveData={this.state.receiveData}
          mode={this.props.multiple ? 'multiple' : 'single'}
          orgData={orgTree} // 树形数据源
        />
      </>
    );
  }
}

const mapStateToProps = (state: ConnectState) => ({
  orgTree: state.common.orgTree
});

const mapDispatchToProps = (dispatch) => ({
  getOrgTree: () => dispatch({ type: 'common/getOrgTreeDataSaga' })
});

export const ContractSelectWithConnect = connect(mapStateToProps, mapDispatchToProps)(ContractSelect);
